<?php
namespace app\common\process;

class UserCartInfo extends Info {
    public function set_num($user) {
    	$validate = $this->validate;
    	$model = $this->model;

        $post = input('post.');
        $post[$this->uid] = $user[$this->upk];
        if(!$validate->scene('set_num')->check($post)) {
        	$this->error($validate->getError());
        }
        $row = loadOnly('Model')->find($model, $post['id']);
        return $row->save(['num' => $post['num']]);
    }

    //保存数据
    public function save($user) {
        $model = $this->model;
        $validate = $this->validate;

        $post = $this->get_save_data();
        $post[$this->uid] = $user[$this->upk];
        $pk = $this->pk;
        if (!$validate->scene($this->saveScene)->check($post)) {
            $this->error($validate->getError());
        }
        try {
            $model->startTrans();
            $this->before_save($model, $post);
            if(isset($post[$pk]) && $post[$pk]) {
                $model->allowField(true)->save($post, [$pk => $post[$pk]]);

            } else {
            	$row = $model->where([
            		'uid' => $post['uid'],
            		'sid' => $post['sid'],
            		'pid' => $post['pid'],
            		'psid' => $post['psid']
            	])->find();
            	if($row) {
            		$model = $row;
            		$model->setInc('num', $post['num']);
            	} else {
            		$model->allowField(true)->save($post);
            	}
                $post[$pk] = $model->getLastInsID();
            }
            $this->after_save($model, $post, $post[$pk]);
            $model->commit();
        } catch(\Exception $e) {
            $model->rollback();
            $this->error($e->getMessage());
        }


        $this->assign($pk, $model->$pk);
        return $this->fetch();
    }
}